package com.dream.mqpushserver.netty;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;

import java.util.List;

/**
 * @author song_
 * @Date 2020/3/26
 * @desc
 **/
public class DeCoder extends ByteToMessageDecoder {

    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
        int readableLength = in.readableBytes();
        System.out.println("readable length " + readableLength);
        if (readableLength < 4) {
            // this is a bad data , less than the first filed 'totalLength' length
            System.out.println("this is a bad data , less than the first filed 'totalLength' length");
            return;
        }

        //获取初始读指针位置
        int beginIndex = in.readerIndex();
        // 读取总长度
        int totalLength = in.readInt();
        if (readableLength < totalLength) {
            // this is a half package, because this readable length less than total length
            // rollback read ptr
            System.out.println(String.format("this is a half package, because this readable %s length less than total length %s", readableLength, totalLength));
            in.readerIndex(beginIndex);
            return;
        }

        // 说明至少有一个完整的数据包, 读取一个数据包
        int headerLength = in.readInt();
        ByteBuf headerData = in.readBytes(headerLength);
        ByteBuf body = in.readBytes(totalLength - 4 - headerLength);
        RequestCommand command = RequestCommand.buildRequestCommand(headerData, body);
        out.add(command);
        System.out.println("-----------");
        System.out.println();
    }
}
